from django import forms
from django.contrib.auth.password_validation import validate_password
from django.forms import ModelForm

from apps.user.models import User


# 注册校验方法
class RegisterModelForm(ModelForm):
    password2 = forms.CharField(
        label="确认密码",
        max_length=20,
        widget=forms.PasswordInput(),
        required=True
    )
    sms_code = forms.CharField(
        max_length=6,
        min_length=6,
        required=False
    )

    class Meta:
        model = User
        fields = ['username', 'password2', 'password', 'mobile', 'sms_code']
        widgets = {
            'password': forms.PasswordInput()
        }

    # 对表单进行整体校验
    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get('password')
        password2 = cleaned_data.get('password2')
        if password != password2:
            raise forms.ValidationError("两次密码不一致")

        try:
            validate_password(password)
        except forms.ValidationError as e:
            raise forms.ValidationError(f"密码不符合要求: {e}")
        # 返回的这个就是校验通过的数据
        return cleaned_data

    # 重写save方法
    def save(self, commit=True):
        user = super().save(commit=False)
        # 确保 password 字段有值
        password = self.cleaned_data.get('password')
        if password:
            user.set_password(password)

        if commit:
            user.save()

        return user


# 登录校验方法
class LoginModelForm(forms.Form):
    username = forms.CharField(max_length=150, required=True)
    password = forms.CharField(widget=forms.PasswordInput(), required=True)
    remembered = forms.BooleanField(required=False)
